<template>
  <div class="multidimensional-workhours">
    <el-row :gutter="20">
      <el-col :span="24" class="filter-section">
        <el-form :inline="true">
          <el-form-item label="统计维度">
            <el-select
              v-model="selectedDimensions"
              multiple
              collapse-tags
              collapse-tags-tooltip
              placeholder="请选择统计维度"
              @change="handleDimensionsChange"
            >
              <el-option label="所属" value="affiliation" />
              <el-option label="一级部门" value="dept1" />
              <el-option label="二级部门" value="dept2" />
              <el-option label="三级部门" value="dept3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadData">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    
    <el-row :gutter="20">
      <el-col :xs="24" :md="8">
        <el-card class="summary-card">
          <h3>工时统计汇总</h3>
          <div v-if="loading" class="loading-container">
            <el-skeleton animated :rows="5" />
          </div>
          <div v-else-if="!workhoursData" class="no-data">
            <el-empty description="暂无数据" />
          </div>
          <div v-else class="summary-list">
            <div class="summary-item">
              <div class="item-label">总白班工时</div>
              <div class="item-value">{{ workhoursData.summary.total_day_hours.toFixed(1) }} 小时</div>
            </div>
            <div class="summary-item">
              <div class="item-label">总晚班工时</div>
              <div class="item-value">{{ workhoursData.summary.total_night_hours.toFixed(1) }} 小时</div>
            </div>
            <div class="summary-item">
              <div class="item-label">总加班工时</div>
              <div class="item-value">{{ workhoursData.summary.total_overtime_hours.toFixed(1) }} 小时</div>
            </div>
            <div class="summary-item">
              <div class="item-label">总记录数</div>
              <div class="item-value">{{ workhoursData.summary.total_records }} 条</div>
            </div>
            <div class="summary-item">
              <div class="item-label">统计时段</div>
              <div class="item-value">{{ workhoursData.summary.period }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :md="16">
        <el-card class="chart-card">
          <div class="chart-header">
            <h3>工时分布图表</h3>
            <div class="chart-actions">
              <el-radio-group v-model="chartType" size="small" @change="handleChartTypeChange">
                <el-radio-button label="stack">堆叠视图</el-radio-button>
                <el-radio-button label="line">趋势视图</el-radio-button>
                <el-radio-button label="pie">占比视图</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div v-if="loading" class="loading-container">
            <el-skeleton animated :rows="5" />
          </div>
          <div v-else-if="!workhoursData || workhoursData.data.length === 0" class="no-data">
            <el-empty description="暂无数据" />
          </div>
          <div v-else class="chart-container">
            <div ref="chartRef" style="width: 100%; height: 400px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="mt-20">
      <el-col :span="24">
        <el-card class="statistics-card">
          <template #header>
            <div class="card-header">
              <h3>工时详细数据</h3>
              <el-button type="primary" size="small" @click="exportToExcel">导出Excel</el-button>
            </div>
          </template>
          <div v-if="loading" class="loading-container">
            <el-skeleton animated :rows="5" />
          </div>
          <div v-else-if="!workhoursData || workhoursData.data.length === 0" class="no-data">
            <el-empty description="暂无数据" />
          </div>
          <div v-else>
            <el-table 
              :data="workhoursData.data" 
              border 
              stripe 
              style="width: 100%; min-width: 1000px;" 
              max-height="500"
            >
              <el-table-column 
                v-for="dimension in workhoursData.dimensions" 
                :key="dimension" 
                :prop="dimension" 
                :label="getDimensionLabel(dimension)" 
                min-width="120"
              />
              <el-table-column prop="day_total_hours" label="白班工时" min-width="100">
                <template #default="scope">
                  {{ scope.row.day_total_hours.toFixed(1) }} 小时
                  <el-tag size="small" type="info" class="ml-5">
                    {{ scope.row.day_hours_percentage.toFixed(1) }}%
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="night_hours" label="晚班工时" min-width="100">
                <template #default="scope">
                  {{ scope.row.night_hours.toFixed(1) }} 小时
                  <el-tag size="small" type="info" class="ml-5">
                    {{ scope.row.night_hours_percentage.toFixed(1) }}%
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="overtime_hours" label="加班工时" min-width="100">
                <template #default="scope">
                  {{ scope.row.overtime_hours.toFixed(1) }} 小时
                  <el-tag size="small" type="info" class="ml-5">
                    {{ scope.row.overtime_hours_percentage.toFixed(1) }}%
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="record_count" label="记录数" min-width="80" />
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, defineProps, defineExpose, nextTick, onUnmounted } from 'vue'
import { useStatisticsStore, type MultidimensionalWorkhoursResponse } from '@/stores/statistics'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'
import * as XLSX from 'xlsx'
import type { CallbackDataParams, TooltipFormatterCallback } from 'echarts/types/dist/shared'
import { graphic, type PieSeriesOption } from 'echarts'

// 定义属性
const props = defineProps({
  startDate: {
    type: String,
    required: true
  },
  endDate: {
    type: String,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  }
})

// 准备状态
const workhoursData = ref<MultidimensionalWorkhoursResponse | null>(null)
const loading = ref(false)
const selectedDimensions = ref<string[]>(['dept1']) // 默认选择一级部门
const chartRef = ref<HTMLElement | null>(null)
const chart = ref<echarts.ECharts | null>(null)
const chartType = ref<'stack' | 'pie' | 'line'>('stack') // 图表类型：堆叠柱状图、折线图或饼图

// 获取store
const statisticsStore = useStatisticsStore()

// 维度标签映射
const dimensionLabels: Record<string, string> = {
  'affiliation': '所属',
  'dept1': '一级部门',
  'dept2': '二级部门',
  'dept3': '三级部门'
}

// 获取维度标签
const getDimensionLabel = (dimension: string): string => {
  return dimensionLabels[dimension] || dimension
}

// 获取维度显示内容
const getDimensionDisplay = (item: any): string => {
  if (!workhoursData.value) return ''
  return workhoursData.value.dimensions.map(dim => item[dim]).join('-')
}

// 处理维度变化
const handleDimensionsChange = () => {
  if (selectedDimensions.value.length === 0) {
    ElMessage.warning('请至少选择一个统计维度')
    selectedDimensions.value = ['dept1'] // 默认选择一级部门
    return
  }
  
  // 维度变化时自动加载数据
  loadData()
}

// 加载多维度工时统计数据
const loadData = async () => {
  if (selectedDimensions.value.length === 0) {
    ElMessage.warning('请至少选择一个统计维度')
    return
  }
  
  loading.value = true
  try {
    // 先销毁现有图表实例
    if (chart.value) {
      chart.value.dispose()
      chart.value = null
    }

    const data = await statisticsStore.getMultidimensionalWorkhours(
      selectedDimensions.value,
      props.startDate, 
      props.endDate
    )
    
    if (data) {
      workhoursData.value = data
      console.log('数据加载完成，准备渲染图表:', {
        hasData: !!data,
        dimensions: data.dimensions,
        dataLength: data.data.length
      })
      
      // 使用nextTick和setTimeout的组合来确保DOM已经更新
      nextTick(() => {
        setTimeout(() => {
          // 确保DOM元素存在
          if (!chartRef.value) {
            const chartContainer = document.querySelector('.chart-container')
            if (chartContainer) {
              const chartDiv = chartContainer.querySelector('div')
              if (chartDiv) {
                console.log('找到图表DOM元素')
                chartRef.value = chartDiv as HTMLElement
              }
            }
          }

          if (chartRef.value && workhoursData.value) {
            console.log('开始渲染图表')
            // 创建新的图表实例
            chart.value = echarts.init(chartRef.value)
            renderChart()
          } else {
            console.error('无法渲染图表:', {
              hasChartRef: !!chartRef.value,
              hasData: !!workhoursData.value
            })
          }
        }, 100)
      })
    }
  } catch (error: any) {
    ElMessage.error(`加载多维度工时统计数据失败: ${error.message}`)
    console.error('加载多维度工时统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理图表类型变化
const handleChartTypeChange = () => {
  console.log('图表类型变更为:', chartType.value)
  nextTick(() => {
    if (workhoursData.value && workhoursData.value.data.length > 0) {
      renderChart()
    }
  })
}

// 监听窗口大小变化，自动调整图表大小
const handleResize = () => {
  if (chart.value && !chart.value.isDisposed()) {
    console.log('窗口大小变化，调整图表大小')
    chart.value.resize()
  }
}

// 在组件setup阶段注册全局事件监听和清理
onMounted(() => {
  console.log('组件挂载完成，初始化图表')
  window.addEventListener('resize', handleResize)
  
  // 确保图表容器DOM元素存在
  nextTick(() => {
    if (!chartRef.value) {
      const chartContainer = document.querySelector('.chart-container')
      if (chartContainer) {
        const chartDiv = chartContainer.querySelector('div')
        if (chartDiv) {
          console.log('组件挂载时找到图表DOM元素')
          chartRef.value = chartDiv as HTMLElement
        }
      }
    }
    
    // 初始加载数据
    loadData()
  })
})

// 组件卸载时清理
onUnmounted(() => {
  console.log('组件卸载，清理资源')
  window.removeEventListener('resize', handleResize)
  if (chart.value) {
    chart.value.dispose()
    chart.value = null
  }
})

// 渲染图表
const renderChart = () => {
  console.log('renderChart被调用:', {
    hasChartRef: !!chartRef.value,
    hasChart: !!chart.value,
    hasData: !!workhoursData.value
  })

  if (!chartRef.value || !workhoursData.value || workhoursData.value.data.length === 0) {
    console.warn('无法渲染图表：DOM元素或数据不存在', {
      chartRef: !!chartRef.value,
      workhoursData: !!workhoursData.value,
      dataLength: workhoursData.value?.data.length
    })
    return
  }

  try {
    // 确保图表实例存在
    if (!chart.value || chart.value.isDisposed()) {
      console.log('创建新的图表实例')
      chart.value = echarts.init(chartRef.value)
    }

    // 准备数据
    const data = workhoursData.value.data
    const dimensions = workhoursData.value.dimensions
    
    // 获取维度组合的标签
    const labels = data.map(item => {
      return dimensions.map(dim => item[dim]).join('-')
    })
    
    // 总计工时 - 用于计算百分比高度
    const totalHoursByLabel: Record<string, number> = {}
    data.forEach((item) => {
      totalHoursByLabel[dimensions.map(dim => item[dim]).join('-')] = item.day_total_hours + item.night_hours + item.overtime_hours
    })

    // 基于图表类型选择渲染方法
    if (chartType.value === 'pie') {
      // 渲染饼图
      renderPieChart(data, labels)
    } else if (chartType.value === 'line') {
      // 渲染折线图
      renderLineChart(data, labels)
    } else {
      // 确定图表类型 - 当数据超过5个类别时改用条形图以提高可读性
      const useBarChart = labels.length > 5
      
      // 渲染堆叠柱状图
      renderStackChart(data, labels, useBarChart, totalHoursByLabel)
    }
  } catch (error) {
    console.error('渲染多维度工时统计图表时发生错误:', error)
  }
}

// 渲染堆叠柱状图
const renderStackChart = (
  data: MultidimensionalWorkhoursResponse['data'], 
  labels: string[], 
  useBarChart: boolean, 
  totalHoursByLabel: Record<string, number>
) => {
  // 准备图表配置
  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      backgroundColor: 'rgba(13, 25, 48, 0.9)',
      borderColor: 'rgba(0, 128, 255, 0.3)',
      borderWidth: 1,
      textStyle: { color: '#fff' },
      formatter: function(params: any) {
        let tooltip = `<div style="font-weight:bold;margin-bottom:5px">${params[0].name}</div>`
        let totalHours = 0
        
        params.forEach((param: any) => {
          totalHours += param.value as number
          let color: string = param.color;
          if (param.color instanceof graphic.LinearGradient) {
            color = 'linear-gradient(to right, ' + param.color.colorStops[0].color + ', ' + param.color.colorStops[1].color + ')';
          }
          tooltip += `<div style="display:flex;justify-content:space-between;align-items:center;margin:5px 0">
            <span style="display:inline-block;margin-right:5px;width:10px;height:10px;background:${color};border-radius:50%"></span>
            <span style="flex:1;text-align:left">${param.seriesName}:</span>
            <span style="font-weight:bold">${(param.value as number).toFixed(1)}小时</span>
            <span style="margin-left:5px">(${( (param.value as number) / totalHoursByLabel[param.name as string] * 100).toFixed(1)}%)</span>
          </div>`
        })
        
        tooltip += `<div style="margin-top:5px;padding-top:5px;border-top:1px solid rgba(255,255,255,0.2)">
          <span>总计: ${totalHours.toFixed(1)}小时</span>
        </div>`
        
        return tooltip
      }
    },
    legend: {
      data: ['白班工时', '晚班工时', '加班工时'],
      textStyle: { color: '#606266' },
      icon: 'roundRect',
      itemWidth: 15,
      itemHeight: 10,
      itemGap: 20,
      bottom: useBarChart ? 0 : 'auto'
    },
    grid: {
      left: useBarChart ? '15%' : '3%',
      right: '4%',
      bottom: useBarChart ? '15%' : '10%',
      top: '8%',
      containLabel: true
    },
    [useBarChart ? 'yAxis' : 'xAxis']: {
      type: 'category',
      data: labels,
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: {
        interval: 0,
        rotate: useBarChart ? 0 : 30,
        fontSize: 12,
        color: '#606266',
        formatter: function(value: string) {
          // 如果标签太长，截断并添加省略号
          if (value.length > 15) {
            return value.substring(0, 13) + '...'
          }
          return value
        }
      }
    },
    [useBarChart ? 'xAxis' : 'yAxis']: {
      type: 'value',
      name: '工时 (小时)',
      nameTextStyle: {
        padding: [0, 0, 0, 10],
        color: '#606266'
      },
      axisLabel: {
        formatter: '{value} h',
        color: '#606266'
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ebeef5'
        }
      }
    },
    series: [
      {
        name: '白班工时',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series',
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0,0,0,0.2)'
          }
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#4facfe' },
            { offset: 1, color: '#00f2fe' }
          ]),
          borderRadius: [useBarChart ? 0 : 4, useBarChart ? 0 : 4, 0, 0]
        },
        data: data.map(item => item.day_total_hours) as number[]
      },
      {
        name: '晚班工时',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series',
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0,0,0,0.2)'
          }
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#84fab0' },
            { offset: 1, color: '#8fd3f4' }
          ]),
          borderRadius: [useBarChart ? 0 : 4, useBarChart ? 0 : 4, 0, 0]
        },
        data: data.map(item => item.night_hours) as number[]
      },
      {
        name: '加班工时',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series',
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0,0,0,0.2)'
          }
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#ffcc33' },
            { offset: 1, color: '#ff9933' }
          ]),
          borderRadius: [useBarChart ? 0 : 4, useBarChart ? 0 : 4, 0, 0]
        },
        data: data.map(item => item.overtime_hours) as number[],
        // 添加标签，显示总工时
        label: {
          show: true,
          position: 'top',
          formatter: function(params: CallbackDataParams) {
            // 计算总和并保留一位小数
            const index = params.dataIndex as number
            const total = data[index].day_total_hours + data[index].night_hours + data[index].overtime_hours
            return total.toFixed(1) + 'h'
          },
          fontSize: 12,
          color: '#606266'
        }
      }
    ],
    animationDuration: 1500,
    animationEasing: 'elasticOut'
  }

  // 设置图表配置
  chart.value!.setOption(option)
  console.log('多维度工时统计堆叠图渲染完成')
}

// 渲染饼图
const renderPieChart = (data: MultidimensionalWorkhoursResponse['data'], labels: string[]) => {
  // 生成不同组合的颜色
  const generateColorList = (num: number) => {
    const colorList = [
      ['#FF6F61', '#F9B5AC'], // 珊瑚红
      ['#6B5B95', '#A89CC8'], // 梅子紫
      ['#88B04B', '#C1D6A2'], // 绿野鼠尾草
      ['#92A8D1', '#C4D3E9'], // 宁静蓝
      ['#955251', '#C4A3A2'], // 烘焙棕
      ['#B565A7', '#D9B3D1'], // 紫水晶
      ['#009B77', '#7FCDBD'], // 绿宝石
      ['#DD4124', '#EDA08C'], // 燃烧橙
      ['#D65076', '#EBAA1D'], // 熏衣草花瓣
      ['#45B8AC', '#A5DBD7'], // 水绿荷叶
    ]
    
    if (num <= colorList.length) {
      return colorList.slice(0, num)
    }
    
    // 如果颜色不够，循环使用
    const result = []
    for (let i = 0; i < num; i++) {
      result.push(colorList[i % colorList.length])
    }
    return result
  }
  
  // 准备三种不同的数据系列
  const preparePieData = (data: MultidimensionalWorkhoursResponse['data'], labels: string[], field: keyof (MultidimensionalWorkhoursResponse['data'][number])) => {
    return data.map((item, index) => {
      return {
        name: labels[index],
        value: item[field]
      }
    }).filter(item => (item.value as number) > 0)
  }
  
  const dayHoursData = preparePieData(data, labels, 'day_total_hours')
  const nightHoursData = preparePieData(data, labels, 'night_hours')
  const overtimeHoursData = preparePieData(data, labels, 'overtime_hours')
  
  // 颜色列表
  const dayColors = generateColorList(dayHoursData.length).map(color => 
    new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: color[0] },
      { offset: 1, color: color[1] }
    ])
  )
  
  const nightColors = generateColorList(nightHoursData.length).map(color => 
    new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: color[0] },
      { offset: 1, color: color[1] }
    ])
  )
  
  const overtimeColors = generateColorList(overtimeHoursData.length).map(color => 
    new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: color[0] },
      { offset: 1, color: color[1] }
    ])
  )
  
  const option: EChartsOption = {
    title: [{
      text: '白班工时分布',
      left: '16.6%',
      top: '83%',
      textStyle: {
        color: '#409EFF',
        fontSize: 14,
        fontWeight: 'normal'
      }
    }, {
      text: '晚班工时分布',
      left: '50%',
      top: '83%',
      textStyle: {
        color: '#67C23A',
        fontSize: 14,
        fontWeight: 'normal'
      }
    }, {
      text: '加班工时分布',
      left: '83.3%',
      top: '83%',
      textStyle: {
        color: '#E6A23C',
        fontSize: 14,
        fontWeight: 'normal'
      }
    }],
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} 小时 ({d}%)',
      backgroundColor: 'rgba(13, 25, 48, 0.9)',
      borderColor: 'rgba(0, 128, 255, 0.3)',
      borderWidth: 1,
      textStyle: { color: '#fff' }
    },
    legend: {
      show: false,
    },
    series: [
      {
        name: '白班工时',
        type: 'pie',
        radius: ['30%', '45%'],
        center: ['16.6%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: false
        },
        data: dayHoursData as PieSeriesOption['data'],
        color: dayColors
      },
      {
        name: '晚班工时',
        type: 'pie',
        radius: ['30%', '45%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: false
        },
        data: nightHoursData as PieSeriesOption['data'],
        color: nightColors
      },
      {
        name: '加班工时',
        type: 'pie',
        radius: ['30%', '45%'],
        center: ['83.3%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: false
        },
        data: overtimeHoursData as PieSeriesOption['data'],
        color: overtimeColors
      }
    ],
    animationDuration: 1500,
    animationEasing: 'elasticOut'
  }

  // 设置图表配置
  chart.value!.setOption(option)
  console.log('多维度工时统计饼图渲染完成')
}

// 渲染折线图
const renderLineChart = (data: MultidimensionalWorkhoursResponse['data'], labels: string[]) => {
  // 排序数据以确保图表有意义
  const sortedData = [...data].sort((a, b) => {
    const totalA = a.day_total_hours + a.night_hours + a.overtime_hours
    const totalB = b.day_total_hours + b.night_hours + b.overtime_hours
    return totalB - totalA // 降序排列
  })
  
  // 只取前10个数据点防止图表过于拥挤
  const limitedData = sortedData.slice(0, 10)
  const limitedLabels = limitedData.map((item) => {
    return workhoursData.value!.dimensions.map(dim => item[dim]).join('-')
  })
  
  // 准备图表配置
  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        lineStyle: {
          color: 'rgba(0,0,0,0.2)',
          width: 1,
          type: 'solid'
        }
      },
      backgroundColor: 'rgba(13, 25, 48, 0.9)',
      borderColor: 'rgba(0, 128, 255, 0.3)',
      borderWidth: 1,
      textStyle: { color: '#fff' }
    },
    legend: {
      data: ['白班工时', '晚班工时', '加班工时'],
      textStyle: { color: '#606266' },
      icon: 'circle',
      itemWidth: 10,
      itemHeight: 10,
      itemGap: 20,
      top: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: limitedLabels,
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: {
        interval: 0,
        rotate: 30,
        fontSize: 12,
        color: '#606266',
        formatter: function(value: string) {
          // 如果标签太长，截断并添加省略号
          if (value.length > 12) {
            return value.substring(0, 10) + '...'
          }
          return value
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '工时 (小时)',
      nameTextStyle: {
        padding: [0, 0, 0, 10],
        color: '#606266'
      },
      axisLabel: {
        formatter: '{value} h',
        color: '#606266'
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ebeef5'
        }
      }
    },
    series: [
      {
        name: '白班工时',
        type: 'line',
        smooth: true,
        symbol: 'emptyCircle',
        symbolSize: 8,
        emphasis: {
          scale: true
        },
        lineStyle: {
          width: 3,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: '#4facfe'
            }, {
              offset: 1, color: '#00f2fe'
            }]
          }
        },
        itemStyle: {
          color: '#4facfe',
          borderColor: '#fff',
          borderWidth: 2
        },
        areaStyle: {
          opacity: 0.2,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#4facfe' },
            { offset: 1, color: 'rgba(0, 242, 254, 0.1)' }
          ])
        },
        data: limitedData.map(item => item.day_total_hours) as number[]
      },
      {
        name: '晚班工时',
        type: 'line',
        smooth: true,
        symbol: 'emptyCircle',
        symbolSize: 8,
        emphasis: {
          scale: true
        },
        lineStyle: {
          width: 3,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: '#84fab0'
            }, {
              offset: 1, color: '#8fd3f4'
            }]
          }
        },
        itemStyle: {
          color: '#84fab0',
          borderColor: '#fff',
          borderWidth: 2
        },
        areaStyle: {
          opacity: 0.2,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#84fab0' },
            { offset: 1, color: 'rgba(143, 211, 244, 0.1)' }
          ])
        },
        data: limitedData.map(item => item.night_hours) as number[]
      },
      {
        name: '加班工时',
        type: 'line',
        smooth: true,
        symbol: 'emptyCircle',
        symbolSize: 8,
        emphasis: {
          scale: true
        },
        lineStyle: {
          width: 3,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: '#ffcc33'
            }, {
              offset: 1, color: '#ff9933'
            }]
          }
        },
        itemStyle: {
          color: '#ffcc33',
          borderColor: '#fff',
          borderWidth: 2
        },
        areaStyle: {
          opacity: 0.2,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#ffcc33' },
            { offset: 1, color: 'rgba(255, 153, 51, 0.1)' }
          ])
        },
        data: limitedData.map(item => item.overtime_hours) as number[]
      }
    ],
    animationDuration: 1500,
    animationEasing: 'cubicOut'
  }

  // 设置图表配置
  chart.value!.setOption(option)
  console.log('多维度工时统计折线图渲染完成')
}

// 导出Excel
const exportToExcel = () => {
  if (!workhoursData.value || workhoursData.value.data.length === 0) {
    ElMessage.warning('没有数据可导出')
    return
  }
  
  try {
    // 准备导出数据
    const exportData = workhoursData.value.data.map(item => {
      const row: Record<string, any> = {}
      
      // 添加维度字段
      workhoursData.value!.dimensions.forEach(dim => {
        row[getDimensionLabel(dim)] = item[dim]
      })
      
      // 添加工时字段
      row['白班工时(小时)'] = item.day_total_hours.toFixed(1)
      row['晚班工时(小时)'] = item.night_hours.toFixed(1)
      row['加班工时(小时)'] = item.overtime_hours.toFixed(1)
      row['白班工时占比(%)'] = item.day_hours_percentage.toFixed(1)
      row['晚班工时占比(%)'] = item.night_hours_percentage.toFixed(1)
      row['加班工时占比(%)'] = item.overtime_hours_percentage.toFixed(1)
      row['记录数'] = item.record_count
      
      return row
    })
    
    // 创建工作簿
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.json_to_sheet(exportData)
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '多维度工时统计')
    
    // 导出文件
    const fileName = `多维度工时统计_${props.startDate}_${props.endDate}.xlsx`
    XLSX.writeFile(wb, fileName)
    
    ElMessage.success('导出成功')
  } catch (error: any) {
    ElMessage.error(`导出失败: ${error.message}`)
    console.error('导出Excel失败:', error)
  }
}

// 监听日期变化，重新加载数据
watch([() => props.startDate, () => props.endDate], () => {
  loadData()
})

// 强制重新渲染图表
const forceRenderChart = () => {
  console.log('强制重新渲染多维度工时统计图表');
  // 清除现有图表实例，确保重新创建
  if (chart.value) {
    chart.value.dispose();
    chart.value = null;
  }
  
  // 给DOM足够的时间进行更新
  nextTick(() => {
    setTimeout(() => {
      // 尝试获取图表DOM元素
      if (!chartRef.value) {
        const chartContainer = document.querySelector('.chart-container');
        if (chartContainer) {
          const chartDiv = chartContainer.querySelector('div');
          if (chartDiv) {
            console.log('找到图表DOM元素，重新分配引用');
            chartRef.value = chartDiv as HTMLElement;
          }
        }
      }
      
      if (chartRef.value && workhoursData.value) {
        renderChart();
      } else {
        console.error('无法获取图表DOM元素或数据');
      }
    }, 500);
  });
};

// 添加组件激活钩子，在组件激活时确保图表能够正确渲染
const ensureChartRendered = () => {
  // 如果已经有图表实例且运行正常，则不需要重新渲染
  if (chart.value && !chart.value.isDisposed() && chartRef.value) {
    return
  }
  
  if (workhoursData.value && workhoursData.value.data.length > 0) {
    nextTick(() => {
      // 给DOM充分时间来更新
      setTimeout(() => {
        if (chartRef.value && (!chart.value || chart.value.isDisposed())) {
          renderChart()
        }
      }, 200)
    })
  }
}

// 暴露方法供父组件调用
defineExpose({
  loadData,
  forceRenderChart
})
</script>

<style scoped>
.multidimensional-workhours {
  margin-bottom: 20px;
  max-height: 85vh; /* 设置最大高度，例如视口高度的85% */
  overflow-y: auto; /* 垂直方向滚动 */
}

.filter-section {
  margin-bottom: 20px;
}

.summary-card,
.chart-card {
  height: 100%;
  margin-bottom: 20px;
}

.summary-card h3,
.chart-card h3 {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 16px;
  color: #606266;
}

.summary-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px dashed #ebeef5;
}

.item-label {
  color: #606266;
  font-size: 14px;
}

.item-value {
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.loading-container, .no-data {
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.chart-container {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mt-20 {
  margin-top: 20px;
}

.ml-5 {
  margin-left: 5px;
}

/* 添加新的表格样式 */
.alternate-chart {
  width: 100%;
  height: 100%;
  overflow: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  border-spacing: 0;
}

.data-table th, .data-table td {
  padding: 12px 8px;
  text-align: left;
  border-bottom: 1px solid #EBEEF5;
}

.data-table th {
  background-color: #F5F7FA;
  color: #606266;
  font-weight: 500;
}

.data-table tr:hover {
  background-color: #F5F7FA;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  color: #606266;
}

.chart-actions {
  display: flex;
  align-items: center;
}

.statistics-card {
  min-height: 550px; /* Ensure card has enough height */
}

.statistics-card .el-card__body {
  max-height: calc(100vh - 250px);
  overflow-y: auto;
  overflow-x: auto;
}

/* 之前设置的detail-card样式，如果适用可以保留 */
.detail-card .el-card__body {
  /* min-height: 400px; */ /* 移除或注释掉此行 */
}
</style> 